package com.usian.admin.service.impl;/*
 *文件名：UserLoginServiceImpl
 *创建者：宋璟
 *创建时间:2023/2/6 11:07
 *描述: TODO
 */

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.usian.admin.mapper.AdUserMapper;
import com.usian.admin.service.UserLoginService;
import com.usian.jwt.utils.AppJwtUtil;
import com.usian.model.admin.dtos.AdUserDto;
import com.usian.model.admin.pojos.AdUser;
import com.usian.model.base.BaseServiceImpl;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserLoginServiceImpl extends BaseServiceImpl<AdUserMapper, AdUser> implements UserLoginService {
    @Override
    public ResponseResult login(AdUserDto dto) {
        //判断如果dto为空或者账号密码为空返回 参数错误
        if (dto == null || StringUtils.isBlank(dto.getName()) || StringUtils.isBlank(dto.getPassword()))return errorParam;
        //账号不为空给他查出来
        LambdaQueryWrapper<AdUser> w = new LambdaQueryWrapper<>();
        w.eq(AdUser::getName,dto.getName());
        AdUser one = getOne(w);
        //如果没有提示他用户不存在
        if (one == null)return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
        //去出表里加密过的密码
        String tablePwd = one.getPassword();
        //加密过以后的密码
        String s = DigestUtils.md5DigestAsHex((dto.getPassword() + one.getSalt()).getBytes());

        if (tablePwd.equals(s)){
            //创建map集合 key（token）是string value是aduser对象
            Map<String,Object> resultMap = new HashMap<>();
            //创建token  ,把token和 对象（加密的密码）放入map
            resultMap.put("token", AppJwtUtil.getToken(Long.valueOf(one.getId())));
            //不能吧数据返回给前段
            one.setPassword("");
            one.setSalt("");
            resultMap.put("user",one);
            //返回给泛型
            return ResponseResult.okResult(resultMap);
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"密码错误");
    }




























}
